/*=============================================================================================================
 * ListFragment.java
 *
 * 1.프로젝트 : ToYou - 명함관리 어플
 * 2.패 키 지 : com.trillion.toyou
 * 3.작업환경 : Android
 * 2.작 업 자 : 손호준, 최명식
 * 3.작업일자 : 2014.12.09 ~ 2014.12.11
 * 4.내    용 : 메인 리스트를 출력하는 프래그먼트 화면
 * 5.수 정 자 :
 * (1) 손호준
 * 
 * 6.수정일자 : 
 * (1) 2014.12.12 04:57pm
 * 
 * 7.수정내용 :
 * (1) OnItemLongClick 메소드에 삭제기능 추가함
 * 
 * =============================================================================================================*/
package com.trillion.toyou;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListFragment extends Fragment implements OnClickListener, OnItemClickListener, OnLongClickListener, OnItemLongClickListener{
	// 뷰 지정
	View view  = null;
	
	// 플래그먼트 관련
	Fragment frag = null;
	FragmentTransaction trans = null;
	
	// db 관련
	DBHelper db = null;
	
	
	// 리스트 뷰 관련
	ListView lv = null;
	DataAdapter adapter = null;
	LayoutInflater mInflater = null;	
	ArrayList<Data> al = null;
	Context context = null;
	TextView custom_name = null;
	TextView custom_company = null;
	TextView custom_phone = null;	
	
	ImageView new_marker = null;
	
	// 리스트 뷰 클릭 관련
	int pos = -999;
	boolean flag = true;
	
	
	// 내 대표명함 관련	
	TextView myMainName = null;
	TextView myMainPhone = null;
	
	LinearLayout topTitle = null;
	
	ImageButton bt_category =null;
	ImageButton bt_sort =null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		this.view = inflater.inflate(R.layout.list_layout, container , false);
		
		MainActivity.page_check = new MainActivity().BACK_EXIT;
		
		this.trans = getFragmentManager().beginTransaction();

		
		
		this.myMainName  = (TextView)this.view.findViewById(R.id.listLayout_tvMyName);
		this.myMainPhone = (TextView)this.view.findViewById(R.id.listLayout_tvMyPhone);
		
		this.lv = (ListView)this.view.findViewById(R.id.listLayout_lv);

		this.context = getActivity();
		
		
		this.list();
		
		
		
		this.adapter = new DataAdapter(getActivity(), al);
		
		MainActivity.my_main_namecard = db.selectMineOne();
		
		
		if(MainActivity.my_main_namecard.getNid() == 0){

			this.myMainName.setText("");
			this.myMainPhone.setText("여기를 눌러 명함을 선택하세요.");
			
			
			AlertDialog.Builder ad = new AlertDialog.Builder(getActivity());
			
			ad.setTitle("대표명함 생성");
			ad.setMessage("명함이 생성되지 않았습니다.\n대표명함을 생성하세요.");
			
			ad.setCancelable(false);
			
			ad.setPositiveButton("확인", 
					new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							frag = new InputFragment();
							
							trans.replace(R.id.root_layout, frag);
							trans.addToBackStack(null);
							trans.commitAllowingStateLoss();
						}
					});
		
			ad.show();
		}else{
			
			this.myMainName.setText(MainActivity.my_main_namecard.getNname());
			this.myMainPhone.setText(MainActivity.my_main_namecard.getPhoneNum());
			
		}
		
		if(MainActivity.catch_namecard != null){
			
			this.frag = new ResultFragment();
			
			this.trans.replace(R.id.root_layout, this.frag);
			this.trans.addToBackStack(null);
			this.trans.commitAllowingStateLoss();
			
		}
		
		LinearLayout myList = (LinearLayout)this.view.findViewById(R.id.listLayout_myList);
		
		ImageButton btn = (ImageButton)this.view.findViewById(R.id.listLayout_btnFind);
		
		
		this.lv.setAdapter(this.adapter);
		
		
		this.topTitle = (LinearLayout)this.view.findViewById(R.id.listLayout_top);
		

		bt_category = (ImageButton)view.findViewById(R.id.list_layout_category);
		bt_sort = (ImageButton)view.findViewById(R.id.list_layout_sort);
		
		bt_category.setOnClickListener(this);
		bt_sort.setOnClickListener(this);
		
		this.lv.setOnItemClickListener(this);
		this.lv.setOnItemLongClickListener(this);

		ImageButton back = (ImageButton)this.view.findViewById(R.id.listview_exit);
		
		
		
		this.topTitle.setOnClickListener(this);
		btn.setOnClickListener(this);
		myList.setOnClickListener(this);
		back.setOnClickListener(this);
		
		return view;
	}
	
	
	
	
	
	
	public void list()
	{
		EditText et = (EditText)this.view.findViewById(R.id.listLayout_etFind);
	
		this.db = new DBHelper(getActivity(), "toyou", null, 1);
		
		switch(MainActivity.sort_choice)
		{
			case 0:
				this.al = this.db.selectOtherList_name(et.getText().toString(), MainActivity.category_choice);
			break;
			case 1:
				this.al = this.db.selectOtherList_date(et.getText().toString(), MainActivity.category_choice);
			break;
		}
	}
	
	
	
	
	
	
	@Override
	public void onResume() {
		new NfcOnOffChange(this.topTitle, R.drawable.top_bar_on_nfc, R.drawable.top_bar_off_nfc);
		
		Button temp = (Button)this.view.findViewById(R.id.listLayout_handle);
		temp.setTextColor(Color.WHITE);
		
		String[] text = {"전체 / 가나다", "전체 / 최신",
						 "VIP / 가나다", "VIP / 최신",
						 "회사 / 가나다", "회사 / 최신",
						 "지인 / 가나다", "지인 / 최신",
						 "기타 / 가나다", "기타 / 최신"};
		
		
		if(MainActivity.sort_choice == 0 && MainActivity.category_choice == ""){
			temp.setText(text[0]);
		}else if(MainActivity.sort_choice == 1 && MainActivity.category_choice == ""){
			temp.setText(text[1]);
		}else if(MainActivity.sort_choice == 0 && MainActivity.category_choice == "vip"){
			temp.setText(text[2]);
		}else if(MainActivity.sort_choice == 1 && MainActivity.category_choice == "vip"){
			temp.setText(text[3]);
		}else if(MainActivity.sort_choice == 0 && MainActivity.category_choice == "company"){
			temp.setText(text[4]);
		}else if(MainActivity.sort_choice == 1 && MainActivity.category_choice == "company"){
			temp.setText(text[5]);
		}else if(MainActivity.sort_choice == 0 && MainActivity.category_choice == "friends"){
			temp.setText(text[6]);
		}else if(MainActivity.sort_choice == 1 && MainActivity.category_choice == "friends"){
			temp.setText(text[7]);
		}else if(MainActivity.sort_choice == 0 && MainActivity.category_choice == "other"){
			temp.setText(text[8]);
		}else if(MainActivity.sort_choice == 1 && MainActivity.category_choice == "other"){
			temp.setText(text[9]);
		}
		
		
		
		super.onResume();
	}
	
	
	
	
	
	
	
	
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		
		AlertDialog.Builder ad = new AlertDialog.Builder(getActivity());
		
		
		switch (id) {
		case R.id.listLayout_btnFind:
			list();
			this.adapter = new DataAdapter(getActivity(), al);
			this.lv.setAdapter(this.adapter);
			
			break;

		case R.id.listLayout_myList:
			this.frag = new MyFragment();
			
			this.trans.replace(R.id.root_layout, this.frag);
			this.trans.addToBackStack(null);
			this.trans.commitAllowingStateLoss();
			
			break;
		case R.id.listLayout_top:
	         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
	            Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
	            startActivity(intent);
	         } else {
	            Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
	            startActivity(intent);
	         }
			break;
				
		case R.id.list_layout_category:
			
			ad.setTitle("카테고리");
			
			final CharSequence[] item = { "전체", "VIP", "회사", "지인", "기타" };
			final CharSequence[] items = { "", "vip", "company", "friends", "other" };
			ad.setItems(item, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(getActivity(), item[which]+"의 목록을 표시합니다.", Toast.LENGTH_SHORT).show();
					
					MainActivity.category_choice = items[which].toString();

					trans = getFragmentManager().beginTransaction();
					frag = new ListFragment();
					trans.replace(R.id.root_layout, frag);
					trans.addToBackStack(null);
					trans.commitAllowingStateLoss();
					
				}
			});
			ad.show();
			break;
			
		case R.id.list_layout_sort:
			ad.setTitle("정렬방식 선택");
			
			final CharSequence[] item2 = { "가나다순", "최신순"};
			ad.setItems(item2, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(getActivity(), item2[which]+"로 정렬합니다.", Toast.LENGTH_SHORT).show();
					MainActivity.sort_choice = which;	
					
					trans = getFragmentManager().beginTransaction();
					frag = new ListFragment();
					trans.replace(R.id.root_layout, frag);
					trans.addToBackStack(null);
					trans.commitAllowingStateLoss();
				}
			});
			ad.show();
			break;
		case R.id.listview_exit:
			ad.setTitle("종료확인");
			
			ad.setMessage("종료하시겠습니까?");
			
			ad.setNegativeButton("확인", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(getActivity(), "종료되었습니다.", Toast.LENGTH_SHORT).show();
					getActivity().finish();
				}
			});
			
			
			ad.setPositiveButton("취소", null);
			
			
			ad.show();
			
			
			
			
			break;
		}
		
	}
	
	@Override
	public boolean onLongClick(View v) {
		this.onClick(v);
		return false;
	}


	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(this.flag){
			this.pos = position;
			
			Data d = this.al.get(this.pos);
			
			Bundle bundle = new Bundle();
			bundle.putInt("id", d.getNid());
			
			
			this.frag = new ViewFragment();
			this.frag.setArguments(bundle);
			
			this.trans.replace(R.id.root_layout, this.frag);
			this.trans.addToBackStack(null);
			this.trans.commitAllowingStateLoss();
			

			
		}
		this.flag = true;
		
	}
	
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		this.flag = false;
		
		this.pos = position;
		
		final Data d = this.al.get(this.pos);
		
		
		
		
		AlertDialog.Builder ad = new AlertDialog.Builder(getActivity());
		

	
		final CharSequence[] ITEMS = {"T : " + d.getTelNum(), "M : "+d.getPhoneNum()};
		
		ad.setTitle(d.getNname() + " " + d.getGrade() + "님께 전화");
		ad.setItems(ITEMS, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String  temp = ITEMS[which].toString();
				String[] phoneNum = temp.split(" : ");
				Uri uri = Uri.parse("tel:" + phoneNum[1]);
				
				Intent intent = new Intent(Intent.ACTION_CALL, uri);
				startActivity(intent);
			}
		});
		ad.setNegativeButton("취소", null);
		ad.show();

		
		return false;
	}
	
	
	
	
	

	private class DataAdapter extends ArrayAdapter<Data> {
		private LayoutInflater mInflater;
		
		public DataAdapter(Context context, ArrayList<Data> data) {
			super(context, 0, data);	
			
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
		}

		@Override
		public View getView(int position, View v, ViewGroup parent) {
			View view = null;
			if (v == null) {
				view = mInflater.inflate(R.layout.listview_item, null);
			} else {
				view = v;
			}
			final Data data = this.getItem(position);
			if (data != null) {
				custom_name = (TextView) view.findViewById(R.id.tv_oname);
				custom_company = (TextView) view.findViewById(R.id.tv_ocom);
				custom_phone = (TextView) view.findViewById(R.id.tv_ophone);
				new_marker = (ImageView) view.findViewById(R.id.imageView2);
				
				
				custom_name.setText(data.getNname());
				custom_company.setText(data.getCompany());
				custom_phone.setText(data.getPhoneNum());
				String rday = data.getrDate();
				String[]rrday = rday.split(" ");
								
				long now = System.currentTimeMillis();
				Date newdate = new Date(now);
				
				SimpleDateFormat CurTimeFormat = new SimpleDateFormat("yyyy-MM-dd");
				
				String nowday = CurTimeFormat.format(newdate);
				
				if(rrday[0].equals(nowday))
				{
					new_marker.setVisibility(v.VISIBLE);
				}else{
					new_marker.setVisibility(v.GONE);
				}
			}
			return view;
		}
	}
	
	
}
